import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    goodList: [
      {
        name: '诸葛亮',
        price: 1000,
        num: 1,
        checked: false
      },
      {
        name: '蔡文姬',
        price: 1500,
        num: 1,
        checked: false
      },
      {
        name: '妲己',
        price: 2000,
        num: 1,
        checked: false
      },
      {
        name: '鲁班',
        price: 2200,
        num: 1,
        checked: false
      }
    ]
  },
  mutations: {
    subNum (state, index) {
      if (state.goodList[index].num > 1) {
        state.goodList[index].num--
      }
    },
    addNum (state, index) {
      state.goodList[index].num++
    },
    changeX (state, index) {
      state.goodList[index].checked = !state.goodList[index].checked
    },
    // 全选和反选
    allChange (state, bool) {
      state.goodList.forEach(item => (item.checked = bool))
    },
    // 数据删除
    delData (state, index) {
      state.goodList.splice(index, 1)
    },
    // 数据添加
    addData (state, data) {
      state.goodList.push(data)
    }
  },
  actions: {
  },
  modules: {
  },
  getters: {
    totalPrice (state) {
      return (index) => state.goodList[index].num * state.goodList[index].price
    },
    totalChange (state) {
      return state.goodList.every(item => item.checked)
    },
    allPrice (state) {
      return state.goodList.reduce((sum, item) => {
        if (item.checked) {
          sum += item.num * item.price
        }
        return sum
      }, 0)
    }
  }
})
